package com.getpebble.android.notifications.util;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Action;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.RemoteInput;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ObjectUtil;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.PblAndroidAppModel;
import com.getpebble.android.common.model.PblAndroidAppModel.Record;
import com.getpebble.android.notifications.model.PblNotification;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class NotificationUtil {
    private static final Set<String> KEYS_TO_OBFUSCATE = ImmutableSet.of("android.title", "android.subText", "android.text", "groupKey", "android.bigText", "android.support.groupKey", new String[0]);
    private static final Pattern PATTERN_NOTIFICATION_PREF_KEY = Pattern.compile("\\w+(\\.\\w+)+");
    private static final String TAG = NotificationUtil.class.getSimpleName();

    private static class LoadAndroidAppsTask extends PblAsyncTask {
        public static final String TAG = NotificationUtil.TAG;

        private LoadAndroidAppsTask() {
        }

        public boolean doInBackground() {
            boolean z;
            synchronized (NotificationUtil.class) {
                Trace.debug(TAG, "Loading Android apps...");
                PackageManager pm = PebbleApplication.getAppContext().getPackageManager();
                if (pm == null) {
                    Trace.warning(TAG, "PackageManager is null");
                    z = false;
                } else {
                    List<PackageInfo> packageInfoList = pm.getInstalledPackages(0);
                    List<String> currentPackages = PblAndroidAppModel.getAllPackageRecords(PebbleApplication.getAppContext().getContentResolver());
                    for (PackageInfo packageInfo : packageInfoList) {
                        if (currentPackages != null && currentPackages.contains(packageInfo.packageName)) {
                            currentPackages.remove(packageInfo.packageName);
                        }
                        ApplicationInfo appInfo = packageInfo.applicationInfo;
                        if (appInfo == null) {
                            Trace.debug(TAG, "appInfo is null for " + packageInfo.packageName);
                        } else {
                            CharSequence charSeq = appInfo.loadLabel(pm);
                            String applicationName = null;
                            if (charSeq != null) {
                                applicationName = charSeq.toString();
                            }
                            if (pm.getLaunchIntentForPackage(appInfo.packageName) != null) {
                                boolean defaultToggleState = CoreNotifications.getDefaultToggleState(packageInfo.packageName);
                                if (PblAndroidAppModel.insertOrUpdate(PebbleApplication.getAppContext().getContentResolver(), new Record(packageInfo.packageName, applicationName, packageInfo.versionName, defaultToggleState, CoreNotifications.allowSelectionForNotification(packageInfo.packageName, PebbleApplication.getAppContext()), 0, 0))) {
                                    Map<String, Object> dataFields = new HashMap();
                                    dataFields.put("package_name", packageInfo.packageName);
                                    dataFields.put("app_name", applicationName);
                                    dataFields.put("app_version", packageInfo.versionName);
                                    dataFields.put("notifications_enabled", Boolean.valueOf(defaultToggleState));
                                    MobileAppBehavior.logInstalledAndroidApp(dataFields);
                                }
                            }
                        }
                    }
                    for (String currentPackage : currentPackages) {
                        PblAndroidAppModel.delete(PebbleApplication.getAppContext().getContentResolver(), currentPackage);
                    }
                    PblPreferences pblPreferences = new PblPreferences(PebbleApplication.getAppContext());
                    if (pblPreferences.getBooleanData(PrefKey.DONE_NOTIFICATION_PREFS_TO_DB_MIGRATION, false)) {
                        if (!pblPreferences.getBooleanData(PrefKey.DONE_NOTIFICATION_PREFS_TO_DB_MIGRATION_WITH_DELETION, false)) {
                            doMigration(pblPreferences, false);
                        }
                    } else {
                        doMigration(pblPreferences, true);
                    }
                    CoreNotifications.disableNotificationsForNativeApps(PebbleApplication.getAppContext());
                    CoreNotifications.updateAllowedStateForNativeApps(PebbleApplication.getAppContext());
                    CoreNotifications.updateAllowedStateForSMSApps(PebbleApplication.getAppContext());
                    z = true;
                }
            }
            return z;
        }

        private void doMigration(PblPreferences prefs, boolean doDatabaseUpdate) {
            Trace.debug(TAG, "Doing migration of notifications preferences to database... doDatabaseUpdate = " + doDatabaseUpdate);
            Map<String, ?> entries = prefs.getSharedPreferences().getAll();
            Editor prefsEditor = prefs.getSharedPreferences().edit();
            for (String key : entries.keySet()) {
                if (NotificationUtil.PATTERN_NOTIFICATION_PREF_KEY.matcher(key).matches()) {
                    Object value = entries.get(key);
                    if (value instanceof Boolean) {
                        boolean chosen = ((Boolean) value).booleanValue();
                        Trace.debug(TAG, "package '" + key + "' .. chosen = " + chosen);
                        if (doDatabaseUpdate) {
                            PblAndroidAppModel.setChosen(key, chosen, PebbleApplication.getAppContext().getContentResolver());
                        }
                        prefsEditor.remove(key);
                    } else {
                        Trace.warning(TAG, "key '" + key + "'.. not a boolean?");
                    }
                }
            }
            prefsEditor.apply();
            prefs.setBooleanData(PrefKey.DONE_NOTIFICATION_PREFS_TO_DB_MIGRATION, true);
            prefs.setBooleanData(PrefKey.DONE_NOTIFICATION_PREFS_TO_DB_MIGRATION_WITH_DELETION, true);
        }

        public void onTaskSuccess() {
        }

        public void onTaskFailed() {
        }
    }

    public static boolean isServiceEnabled(Context context) {
        if (VERSION.SDK_INT < 18) {
            return AccessibilityServiceUtil.isPebbleAccessibilityEnabled(context);
        }
        boolean enabled = NotificationServiceUtil.isNotificationListenerServiceEnabled(context);
        if (!enabled) {
            return enabled;
        }
        NotificationServiceUtil.verifyNotificationListenerService(context);
        return enabled;
    }

    public static void showEnableServiceActivity(Context context) {
        if (VERSION.SDK_INT >= 18) {
            NotificationServiceUtil.startNotificationListenerSettingsActivity(context);
        } else {
            AccessibilityServiceUtil.enableAccessibilityService(context);
        }
    }

    public static void verifyService(Context context) {
        if (VERSION.SDK_INT >= 18) {
            NotificationServiceUtil.verifyNotificationListenerService(context);
        }
    }

    public static boolean supportsSidechannel() {
        return VERSION.SDK_INT >= 18;
    }

    public static void sendNotificationAnalytics(PblNotification pblNotification, boolean sentToWatch) {
        if (!pblNotification.isOngoing()) {
            Map<String, Object> dataFields = new HashMap();
            dataFields.put("isClearable", pblNotification.isClearable() ? "1" : "0");
            dataFields.put("source", pblNotification.getSource().toString());
            dataFields.put("isDuplicate", pblNotification.isDuplicate() ? "1" : "0");
            dataFields.put("sentToWatch", sentToWatch ? "1" : "0");
            Notification notif = pblNotification.getNotification();
            if (notif != null) {
                int i;
                WearableExtender wearableExtender = new WearableExtender(notif);
                int actionCount = NotificationCompat.getActionCount(notif);
                dataFields.put("actionCount", String.valueOf(actionCount));
                List<Map<String, String>> actions = new ArrayList();
                for (i = 0; i < actionCount; i++) {
                    actions.add(getActionAnalytics(NotificationCompat.getAction(notif, i)));
                }
                dataFields.put("actions", actions);
                dataFields.put("hasContentIntent", notif.contentIntent != null ? "1" : "0");
                dataFields.put("isGroupSummary", NotificationCompat.isGroupSummary(notif) ? "1" : "0");
                dataFields.put("contentAction", String.valueOf(wearableExtender.getContentAction()));
                int pagesCount = 0;
                List<Notification> pages = wearableExtender.getPages();
                if (pages != null) {
                    pagesCount = pages.size();
                }
                dataFields.put("pagesCount", String.valueOf(pagesCount));
                List<Action> wearableActions = wearableExtender.getActions();
                int wearableActionCount = 0;
                if (wearableActions != null) {
                    wearableActionCount = wearableActions.size();
                }
                dataFields.put("wearActionCount", String.valueOf(wearableActionCount));
                List<Map<String, String>> wearActions = new ArrayList();
                for (i = 0; i < wearableActionCount; i++) {
                    wearActions.add(getActionAnalytics((Action) wearableActions.get(i)));
                }
                dataFields.put("wearActions", wearActions);
            }
            Record appRecord = pblNotification.getAppRecord();
            String appName = "";
            String version = "";
            Boolean isEnabled = null;
            if (appRecord != null) {
                appName = appRecord.appName;
                version = appRecord.appVersion;
                isEnabled = Boolean.valueOf(appRecord.chosen);
            }
            dataFields.put("package_name", pblNotification.getPackageName());
            dataFields.put("app_name", appName);
            dataFields.put("app_version", version);
            dataFields.put("notifications_enabled", isEnabled);
            MobileAppBehavior.logNotificationEvent(dataFields);
        }
    }

    private static Map<String, String> getActionAnalytics(Action androidAction) {
        Map<String, String> actionProperties = new HashMap();
        actionProperties.put("Title", androidAction.title.toString());
        RemoteInput[] remoteInputs = androidAction.getRemoteInputs();
        int remoteInputCount = 0;
        if (remoteInputs != null) {
            remoteInputCount = remoteInputs.length;
        }
        actionProperties.put("RemoteInputCount", String.valueOf(remoteInputCount));
        if (remoteInputs != null) {
            for (int j = 0; j < remoteInputCount; j++) {
                actionProperties.put("RemoteInputAllowsFreeform", remoteInputs[j].getAllowFreeFormInput() ? "1" : "0");
                actionProperties.put("RemoteInputLabel", remoteInputs[j].getLabel().toString());
                CharSequence[] choices = remoteInputs[j].getChoices();
                int numChoices = 0;
                int maxChoiceLen = 0;
                if (choices != null) {
                    numChoices = choices.length;
                    for (CharSequence choice : choices) {
                        if (choice.length() > maxChoiceLen) {
                            maxChoiceLen = choice.length();
                        }
                    }
                }
                actionProperties.put("RemoteInputChoicesCount", String.valueOf(numChoices));
                actionProperties.put("RemoteInputChoicesMaxLen", String.valueOf(maxChoiceLen));
            }
        }
        return actionProperties;
    }

    @SuppressLint({"NewApi"})
    public static void dumpNotification(PblNotification pblNotification) {
        try {
            Notification notif = pblNotification.getNotification();
            Trace.verbose(TAG, "dumpNotification() source = " + pblNotification.getSource());
            Trace.verbose(TAG, "package: " + pblNotification.getPackageName() + " tag: " + pblNotification.getAndroidNotificationTag() + " key: " + pblNotification.getAndroidNotificationKey());
            Trace.verbose(TAG, "isOngoing: " + pblNotification.isOngoing() + " id: " + pblNotification.getAndroidNotificationId() + " postTimeLocal: " + pblNotification.getPostTimeLocalMillis() + " isClearable: " + pblNotification.isClearable());
            Trace.verbose(TAG, "isGroupSummary: " + pblNotification.isGroupSummary() + " groupKey: " + pblNotification.getGroupKey());
            String category = null;
            if (notif != null) {
                int i;
                WearableExtender wearableExtender = new WearableExtender(notif);
                if (VERSION.SDK_INT >= 21) {
                    category = notif.category;
                }
                Trace.verbose(TAG, "category: " + category + " number: " + notif.number + " when: " + notif.when);
                Trace.verbose(TAG, "hasContentIntent: " + (notif.contentIntent != null) + " tickerText: " + notif.tickerText + " contentAction: " + wearableExtender.getContentAction());
                Bundle notificationExtras = NotificationCompat.getExtras(notif);
                if (notificationExtras == null) {
                    Trace.verbose(TAG, "> No notification extras\n");
                } else {
                    Trace.verbose(TAG, "> Notification extras: ");
                    dumpExtras(notificationExtras);
                    try {
                        CharSequence[] textLines = notificationExtras.getCharSequenceArray("android.textLines");
                        if (textLines != null) {
                            for (i = 0; i < textLines.length; i++) {
                                Trace.verbose(TAG, ">> TextLine " + i + ": '" + textLines[i] + "'");
                            }
                        }
                    } catch (Exception e) {
                        Trace.verbose(TAG, "Error getting text lines");
                    }
                    try {
                        CharSequence[] people = notificationExtras.getCharSequenceArray("android.people");
                        if (people != null) {
                            for (i = 0; i < people.length; i++) {
                                Trace.verbose(TAG, ">> People " + i + ": '" + people[i] + "'");
                            }
                        }
                    } catch (Exception e2) {
                        Trace.verbose(TAG, "Error getting people");
                    }
                }
                int pagesCount = 0;
                List<Notification> pages = wearableExtender.getPages();
                if (pages != null) {
                    pagesCount = pages.size();
                }
                Trace.verbose(TAG, "pages count = " + pagesCount);
                for (i = 0; i < pagesCount; i++) {
                    Trace.verbose(TAG, "> page " + i + ": " + ((Notification) pages.get(i)).tickerText);
                }
                int actionCount = NotificationCompat.getActionCount(notif);
                Trace.verbose(TAG, "action count: " + actionCount);
                for (i = 0; i < actionCount; i++) {
                    dumpAction(NotificationCompat.getAction(notif, i), i);
                }
                List<Action> wearableActions = wearableExtender.getActions();
                Trace.verbose(TAG, "WearableExtender action count: " + wearableActions.size());
                int i2 = 0;
                for (Action action : wearableActions) {
                    i = i2 + 1;
                    dumpAction(action, i2);
                    i2 = i;
                }
            }
        } catch (Exception e3) {
            Trace.verbose(TAG, "Error dumping sbn", e3);
        }
    }

    private static void dumpAction(Action androidAction, int index) {
        Trace.verbose(TAG, "> Action " + index + ": " + androidAction.title);
        Trace.verbose(TAG, ">> Action Bundle extras");
        dumpExtras(androidAction.getExtras());
        RemoteInput[] remoteInputs = androidAction.getRemoteInputs();
        if (remoteInputs == null) {
            Trace.verbose(TAG, ">> Remote inputs are null");
            return;
        }
        int numRemoteInputs = remoteInputs.length;
        Trace.verbose(TAG, ">> Remote input count: " + numRemoteInputs);
        for (int j = 0; j < numRemoteInputs; j++) {
            Trace.verbose(TAG, ">> Remote input " + j + ": " + remoteInputs[j].getLabel());
            Trace.verbose(TAG, ">> Supports remote input: " + remoteInputs[j].getAllowFreeFormInput());
            Trace.verbose(TAG, ">> Choices: ");
            CharSequence[] choices = remoteInputs[j].getChoices();
            if (choices == null) {
                Trace.verbose(TAG, " none");
            } else {
                for (CharSequence choice : choices) {
                    Trace.verbose(TAG, choice + ", ");
                }
            }
            Trace.verbose(TAG, ">> RemoteInput Bundle extras:");
            dumpExtras(remoteInputs[j].getExtras());
        }
    }

    private static void dumpExtras(Bundle extras) {
        if (extras == null) {
            Trace.verbose(TAG, "null extras");
            return;
        }
        for (String key : extras.keySet()) {
            Object value = extras.get(key);
            String type = "";
            if (value != null) {
                type = value.getClass().getSimpleName();
            }
            if (KEYS_TO_OBFUSCATE.contains(key)) {
                value = value == null ? "<null>" : " (obfuscated): " + ObjectUtil.hash(value);
            }
            Trace.verbose(TAG, ">> Extra: key = " + key + " type = " + type + " value = " + value);
        }
    }

    public static void loadAndroidApps() {
        new LoadAndroidAppsTask().submit();
    }
}
